import { _decorator, Component, Node } from 'cc';
import { llog, lwarn } from '../../sgame/logger/Logger';
import { Vec3 } from 'cc';
import { v3 } from 'cc';
import { randomRangeInt } from 'cc';
import { NodePool } from '../../sgame/pool/NodePool';
const { ccclass, property } = _decorator;

@ccclass('NodePoolTest')
export class NodePoolTest extends Component {
    private _minX: number = -screen.width / 2;
    private _maxX: number = screen.width / 2;
    private _minY: number = -screen.height / 2;
    private _maxY: number = screen.height / 2;

    @property(NodePool)
    public nodePool: NodePool;

    private _nodes: Node[] = [];

    start() {
        this.nodePool.onInstantiate = (node: Node) => {
            llog("instantiate node", node);
        };

        this.nodePool.onPut = (node: Node) => {
            llog("put node", node);
        };

        this.nodePool.onPop = (node: Node) => {
            llog("pop node", node);
            const transform = this.randomTransform();
            node.position = transform.position;
            node.scale = transform.scale;
        };

        lwarn('this.newPrefab(5)');
        this.newPrefab(5);
        lwarn('this.putPrefab()');
        this.putPrefab();
        lwarn('this.newPrefab(10)');
        this.newPrefab(10);
    }

    private newPrefab(len) {
        for (let i = 0; i < len; i++) {
            this._nodes.push(this.nodePool.get());
        }
    }

    private putPrefab() {
        let len: number = this._nodes.length
        for (let i = 0; i < len; i++) {
            this.nodePool.put(this._nodes.pop());
        }
    }

    private randomTransform() {
        let position: Vec3 = v3(randomRangeInt(this._minX, this._maxX), randomRangeInt(this._minY, this._maxY), 0);
        let scale: Vec3 = v3(randomRangeInt(0.5, 1.5), randomRangeInt(0.5, 1.5), 1);
        return {
            position,
            scale
        }
    }
}

